package com.zlj.jsonlib;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/*
 * 演示JSON-LIB小工具
 */
public class JsonlibDemo {
	
	/*
	 * JSONObject 可以当map来用
	 */
	@Test
	public void fun1() {
		JSONObject map = new JSONObject();
		map.put("name", "zhangsan");
		map.put("age", 18);
		map.put("sex", "male");
		System.out.println(map.toString());  //{"name":"zhangsan","age":18,"sex":"male"}
	}

	/*
	 * 当已经有一个person对象时，可以把person对象转换为JSONObject对象
	 */
	@Test
	public void fun2() {
		Person p = new Person("zhangsan",19,"female");
		//把对象转换为JSONObject类型
		JSONObject jsonObject = JSONObject.fromObject(p);
		System.out.println(jsonObject.toString());  //{"age":19,"name":"zhangsan","sex":"female"}
	}
	
	/*
	 * JSONArray
	 */
	@Test
	public void fun3() {
		Person p1 = new Person("zhangsan",19,"female");
		Person p2 = new Person("lisi",29, "male");
		JSONArray list = new JSONArray();
		list.add(p1);
		list.add(p2);
		//[{"age":19,"name":"zhangsan","sex":"female"},{"age":29,"name":"lisi","sex":"male"}]
		System.out.println(list.toString());
	}
	
	/*
	 * 原先就有一个list,则需要把list转换为JSONArray
	 */
	@Test
	public void fun4() {
		Person p1 = new Person("zhangsan",19,"female");
		Person p2 = new Person("lisi",29, "male");
		List<Person> list = new ArrayList<Person>();
		list.add(p1);
		list.add(p2);
		JSONArray jsonArray = JSONArray.fromObject(list);
		//[{"age":19,"name":"zhangsan","sex":"female"},{"age":29,"name":"lisi","sex":"male"}]
		System.out.println(jsonArray.toString());
	}
}
